package com.xnyzc.lhy.mis.service.impl.cms.auditentry;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xnyzc.lhy.common.component.amap.GouldMapUtils;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.constant.RedisPrefixConstant;
import com.xnyzc.lhy.common.entity.GouldLYResult;
import com.xnyzc.lhy.common.entity.Qw;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.common.util.TokenUtil;
import com.xnyzc.lhy.mis.entity.cms.auditentry.OaSysAuditEntry;
import com.xnyzc.lhy.mis.entity.dictionaries.OaSysDict;
import com.xnyzc.lhy.mis.entity.result.user.UserLoginResult;
import com.xnyzc.lhy.mis.entity.sidebar.OaSysOffice;
import com.xnyzc.lhy.mis.entity.system.OaSysGlobalConfig;
import com.xnyzc.lhy.mis.entity.user.OaDUserOffice;
import com.xnyzc.lhy.mis.feign.amap.IAmapService;
import com.xnyzc.lhy.mis.mapper.sidebar.OaSysOfficeMapper;
import com.xnyzc.lhy.mis.mapper.system.OaSysGlobalConfigMapper;
import com.xnyzc.lhy.mis.mapper.user.OaDUserOfficeMapper;
import com.xnyzc.lhy.mis.entity.driver.wallet.OaDWallet;
import com.xnyzc.lhy.mis.entity.result.cms.auditentry.AuditEntry;
import com.xnyzc.lhy.mis.entity.user.OaDUser;
import com.xnyzc.lhy.mis.entity.user.OaDUserInfo;
import com.xnyzc.lhy.mis.entity.vehicle.OaDDriverVehicle;
import com.xnyzc.lhy.mis.entity.vehicle.OaSysVehicle;
import com.xnyzc.lhy.mis.entity.vehicle.OaSysVehicleMdict;
import com.xnyzc.lhy.mis.mapper.cms.auditentry.OaSysAuditEntryMapper;
import com.xnyzc.lhy.mis.mapper.dictionaries.OaSysDictMapper;
import com.xnyzc.lhy.mis.mapper.driver.wallet.OaDWalletMapper;
import com.xnyzc.lhy.mis.mapper.user.OaDUserInfoMapper;
import com.xnyzc.lhy.mis.mapper.user.OaDUserMapper;
import com.xnyzc.lhy.mis.mapper.vehicle.OaDDriverVehicleMapper;
import com.xnyzc.lhy.mis.mapper.vehicle.OaSysVehicleMapper;
import com.xnyzc.lhy.mis.mapper.vehicle.OaSysVehicleMdictMapper;
import com.xnyzc.lhy.mis.service.cms.auditentry.OaSysAuditEntryService;
import com.xnyzc.lhy.resource.entity.amap.AmapTidParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 审核入驻接口实现类
 *
 * @author zhaolijie
 * @date
 */
@Service
public class OaSysAuditEntryServiceImpl implements OaSysAuditEntryService {


    @Autowired
    private OaSysAuditEntryMapper oaSysAuditEntryMapper;

    @Autowired
    private OaSysDictMapper oaSysDictMapper;

    @Autowired
    private OaSysVehicleMdictMapper oaSysVehicleMdictMapper;

    @Autowired
    private OaDUserMapper oaDUserMapper;

    @Autowired
    private OaDUserInfoMapper oaDUserInfoMapper;

    @Autowired
    private OaSysVehicleMapper oaSysVehicleMapper;

    @Autowired
    private OaDDriverVehicleMapper oaDDriverVehicleMapper;

    @Autowired
    private OaDWalletMapper oaDWalletMapper;

    @Autowired
    private OaSysGlobalConfigMapper oaSysGlobalConfigMapper;

    @Autowired
    private IAmapService iAmapService;

    @Autowired
    private OaSysOfficeMapper oaSysOfficeMapper;

    @Autowired
    private OaDUserOfficeMapper oaDUserOfficeMapper;

    public static String serviceId;

    @Value("${global.amap.lyServiceId}")
    public void setServiceId(String amapServiceId) {
        serviceId = amapServiceId;
    }


    /**
     * 审核入驻列表接口
     *
     * @param auditEntryResults
     * @return
     */
    @Override
    public Rv getAuditEntryList(AuditEntry auditEntryResults) {
        if (CheckUtil.objIsEmpty(auditEntryResults.getCurrent(), auditEntryResults.getSize())) {
            throw PangException.create(EErrorCode.missingArg);
        }
        IPage<AuditEntry> auditEntryList = oaSysAuditEntryMapper.getAuditEntryList(new Page(auditEntryResults.getCurrent(), auditEntryResults.getSize()), auditEntryResults);
        return Rv.wrap(auditEntryList);
    }

    /**
     * 获取字典审核状态信息
     *
     * @return
     */
    @Override
    public Rv getDictAuditStatus() {
        QueryWrapper<OaSysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysDict.TYPE, "audit_status");
        List<OaSysDict> oaSysDicts = oaSysDictMapper.selectList(queryWrapper);
        return Rv.wrap(oaSysDicts);
    }

    /**
     * 获取列表详情信息
     *
     * @param auditId：主键ID
     * @return
     */
    @Override
    public Rv getAuditEntryListDetails(String auditId) {
        if (CheckUtil.strIsEmpty(auditId)) {
            throw PangException.create(EErrorCode.missingArg);
        }
        // 开始进行查询
        AuditEntry auditEntryListDetails = this.getAuditEntryListDetailsCustom(auditId);
        if ("1".equals(auditEntryListDetails.getSex())) {
            auditEntryListDetails.setSexName("男");
        } else if ("2".equals(auditEntryListDetails.getSex())) {
            auditEntryListDetails.setSexName("女");
        }
        // 颜色值
        String color = auditEntryListDetails.getColor();
        // 查询对应的车辆颜色
        QueryWrapper<OaSysDict> oaSysDictQueryWrapper = new QueryWrapper<>();
        oaSysDictQueryWrapper.eq(OaSysDict.TYPE, "vegicle_color_type");
        oaSysDictQueryWrapper.eq(OaSysDict.VALUE, color);
        OaSysDict oaSysDict = oaSysDictMapper.selectOne(oaSysDictQueryWrapper);
        auditEntryListDetails.setColorName(oaSysDict.getLabel());
        // 车辆Code
        String vehCode = auditEntryListDetails.getVehCode();
        // 查询车型
        QueryWrapper<OaSysVehicleMdict> oaSysVehicleMdictQueryWrapperModel = new QueryWrapper<>();
        oaSysVehicleMdictQueryWrapperModel.eq(OaSysVehicleMdict.CODE, vehCode);
        OaSysVehicleMdict oaSysVehicleMdictModel = oaSysVehicleMdictMapper.selectOne(oaSysVehicleMdictQueryWrapperModel);

        // 查询车系
        QueryWrapper<OaSysVehicleMdict> oaSysVehicleMdictQueryWrapperSystem = new QueryWrapper<>();
        oaSysVehicleMdictQueryWrapperSystem.eq(OaSysVehicleMdict.MDICT_ID, oaSysVehicleMdictModel.getParentId());
        OaSysVehicleMdict oaSysVehicleMdictSystem = oaSysVehicleMdictMapper.selectOne(oaSysVehicleMdictQueryWrapperSystem);

        // 查询品牌
        QueryWrapper<OaSysVehicleMdict> oaSysVehicleMdictQueryWrapperBrand = new QueryWrapper<>();
        oaSysVehicleMdictQueryWrapperBrand.eq(OaSysVehicleMdict.MDICT_ID, oaSysVehicleMdictSystem.getParentId());
        OaSysVehicleMdict oaSysVehicleMdictBrand = oaSysVehicleMdictMapper.selectOne(oaSysVehicleMdictQueryWrapperBrand);

        //部门信息
        Integer officeCode = auditEntryListDetails.getOfficeCode();
        OaSysOffice office = oaSysOfficeMapper.selectOne(Qw.create().eq(OaSysOffice.CODE, officeCode));

        auditEntryListDetails.setVehicleModelName(oaSysVehicleMdictModel.getName());
        auditEntryListDetails.setVehicleSystemName(oaSysVehicleMdictSystem.getName());
        auditEntryListDetails.setVehicleBrandName(oaSysVehicleMdictBrand.getName());
        auditEntryListDetails.setOfficeName(office.getName());
        auditEntryListDetails.setVehicleName(oaSysVehicleMdictBrand.getName() + "-" + oaSysVehicleMdictSystem.getName() + "-" + oaSysVehicleMdictModel.getName());
        return Rv.wrap(auditEntryListDetails);
    }

    /**
     * 处理审核意见
     *
     * @param auditEntry
     * @return
     */
    @Override
    public Rv handlerAuditEntryRemark(AuditEntry auditEntry) {
        // 主键ID
        Long auditId = auditEntry.getAuditId();
        // 审核状态
        String status = auditEntry.getStatus();
        // 审核意见内容
        String remark = auditEntry.getRemark();
        if (CheckUtil.objIsEmpty(auditId, status, remark)) {
            throw PangException.create(EErrorCode.missingArg);
        }

        AuditEntry auditEntryListDetails = this.getAuditEntryListDetailsCustom(String.valueOf(auditId));
        // 查询该手机号在司机表是否被注册
        QueryWrapper<OaDUser> oaDUserQueryWrapper = new QueryWrapper<>();
        oaDUserQueryWrapper.eq(OaDUser.DRIVER_PHONE, auditEntryListDetails.getDriverPhone());
        Integer selectCountOaDUser = oaDUserMapper.selectCount(oaDUserQueryWrapper);
        if (selectCountOaDUser > 0) {
            throw PangException.create(EErrorCode.phoneRegister);
        }

        // 身份证号是否被注册
        QueryWrapper<OaDUserInfo> oaDUserInfoQueryWrapper = new QueryWrapper<>();
        oaDUserInfoQueryWrapper.eq(OaDUserInfo.IDENTITY_NUMBER, auditEntryListDetails.getIdcard());
        Integer oaDUserInfoSelectCount = oaDUserInfoMapper.selectCount(oaDUserInfoQueryWrapper);
        if (oaDUserInfoSelectCount > 0) {
            throw PangException.create(EErrorCode.userExistError);
        }

        // 查询车牌号是否被注册
        QueryWrapper<OaSysVehicle> oaSysVehicleQueryWrapper = new QueryWrapper<>();
        oaSysVehicleQueryWrapper.eq(OaSysVehicle.VEH_NO, auditEntryListDetails.getCarNo());
        Integer oaSysVehicleCount = oaSysVehicleMapper.selectCount(oaSysVehicleQueryWrapper);
        if (oaSysVehicleCount > 0) {
            throw PangException.create(EErrorCode.userExistError);
        }
        //给司机注册终端
        Long terminalId = 0L;
        /*if (CheckUtil.strIsNotEmpty(serviceId)) {
            String name = auditEntry.getIdcard();
            String desc = auditEntry.getDriverName();
            GouldLYResult result = GouldMapUtils.registGouldLYTerminal(serviceId, name, desc);
            if ("10000".equals(result.getErrcode())) {
                terminalId = result.getData().getTid();
            } else {
                throw PangException.create(EErrorCode.lyServiceError, result.getErrmsg()+": "+serviceId);
            }
        } else {
            throw PangException.create(EErrorCode.lyServiceError, "高德猎鹰服务id不存在，请联系系统管理员！");
        }*/
        OaSysAuditEntry oaSysAuditEntry = new OaSysAuditEntry();
        oaSysAuditEntry.setAuditId(auditId);
        oaSysAuditEntry.setStatus(Integer.valueOf(status));
        oaSysAuditEntry.setRemark(remark);
        long driverId = IDUtil.nextId();
        if (Integer.valueOf(status) == 1) {
            oaSysAuditEntry.setDriverId(driverId);
            oaSysAuditEntry.setDriverPhone(auditEntry.getDriverPhone());
        }
        oaSysAuditEntry.setUpdateTime(new Date());
        oaSysAuditEntry.setUpdateUser(TokenUtil.getTokenUserId());
        int updateById = oaSysAuditEntryMapper.updateById(oaSysAuditEntry);
        if (updateById > 0) {
            if (Integer.valueOf(status) == 1) {
                this.addDUser(auditEntryListDetails, driverId);
                this.addUserInfo(auditEntryListDetails, driverId,terminalId);
                this.addWallet(auditEntryListDetails, driverId);
                this.addVehicleInfo(auditEntryListDetails, driverId);
                this.addOaDUserOffice(driverId, auditEntryListDetails.getOfficeCode());
            }
            throw PangException.create(EErrorCode.success);
        } else {
            throw PangException.create(EErrorCode.updateWalletFailure);
        }
    }

    /**
     * 导出审核入驻信息
     *
     * @param auditEntryResults
     * @return
     */
    @Override
    public Rv exportAuditEntryInfo(AuditEntry auditEntryResults) {
        String driverName = auditEntryResults.getDriverName();
        String status = auditEntryResults.getStatus();
        String residentSerialNumber = auditEntryResults.getResidentSerialNumber();
        String driverPhone = auditEntryResults.getDriverPhone();
        String cityCode = auditEntryResults.getCityCode();
        String sysUserName = auditEntryResults.getSysUserName();
        List<String> cityCodes = auditEntryResults.getCityCodes();
        List<AuditEntry> auditEntries = oaSysAuditEntryMapper.exportAuditEntryInfo(
                driverName, status, residentSerialNumber, driverPhone, cityCode, cityCodes, sysUserName
        );
        return Rv.wrap(auditEntries);
    }


    private AuditEntry getAuditEntryListDetailsCustom(String auditId) {
        return oaSysAuditEntryMapper.getAuditEntryListDetails(auditId);
    }

    private void addDUser(AuditEntry auditEntryListDetails, Long driverId) {
        OaDUser oaDUser = new OaDUser();
        oaDUser.setDriverId(driverId);
        oaDUser.setDriverPhone(auditEntryListDetails.getDriverPhone());
        oaDUser.setLoginAccount(auditEntryListDetails.getDriverPhone());
        oaDUser.setDriverName(auditEntryListDetails.getDriverName());
        oaDUser.setSex(auditEntryListDetails.getSex());
        oaDUser.setTag(TokenUtil.getTag());
        oaDUser.setCreateUser(TokenUtil.getTokenUserId());
        oaDUser.setCreateTime(new Date());
        oaDUser.setUpdateTime(new Date());
        oaDUser.setAccountStatus(0);
        int insert = oaDUserMapper.insert(oaDUser);
        if (insert == 0) {
            throw PangException.create(EErrorCode.addError);
        }
    }

    /**
     * 添加司机信息表
     *
     * @param auditEntryListDetails
     * @param driverId
     */
    private void addUserInfo(AuditEntry auditEntryListDetails, Long driverId,Long terminalId) {
        OaDUserInfo oaDUserInfo = new OaDUserInfo();
        oaDUserInfo.setInfoId(IDUtil.nextId());
        oaDUserInfo.setDriverId(driverId);
        oaDUserInfo.setIdentityNumber(auditEntryListDetails.getIdcard());
        oaDUserInfo.setPassingDate(new Date());
        oaDUserInfo.setAuditType(0);
        oaDUserInfo.setRegisterCityId(Integer.parseInt(auditEntryListDetails.getCityCode()));
        oaDUserInfo.setDriverType(2);
        oaDUserInfo.setAgreement(1);
        oaDUserInfo.setTotalServiceScore(100);
        oaDUserInfo.setBeenDriving(Integer.parseInt(auditEntryListDetails.getDriveAge()));
        oaDUserInfo.setOrderQuantityCompleted(0);
        oaDUserInfo.setTag(TokenUtil.getTag());
        oaDUserInfo.setCreateUser(TokenUtil.getTokenUserId());
        oaDUserInfo.setCreateTime(new Date());
        oaDUserInfo.setUpdateTime(new Date());
        oaDUserInfo.setBankAccountName(auditEntryListDetails.getDriverName());
        oaDUserInfo.setDriverCityId(auditEntryListDetails.getCityCode());
        oaDUserInfo.setTid(terminalId);
        List<OaSysGlobalConfig> oaSysGlobalConfigs = oaSysGlobalConfigMapper.selectList(Wrappers.<OaSysGlobalConfig>lambdaQuery().eq(OaSysGlobalConfig::getTag, TokenUtil.getTag()));
        if (oaSysGlobalConfigs.size() == 1) {
            if (CheckUtil.objIsNotEmpty(oaSysGlobalConfigs.get(0).getGouldServiceId())) {
                AmapTidParam amapTidParam = new AmapTidParam();
                amapTidParam.setClientId(TokenUtil.getClientId());
                amapTidParam.setServiceId(oaSysGlobalConfigs.get(0).getGouldServiceId().toString());
                amapTidParam.setTag(TokenUtil.getTag());
                amapTidParam.setUserId(driverId);
                Long sid = iAmapService.getAmapTid(amapTidParam);
                oaDUserInfo.setTid(sid);
            }
        }
        int insert = oaDUserInfoMapper.insert(oaDUserInfo);
        if (insert == 0) {
            throw PangException.create(EErrorCode.addError);
        }
    }

    /**
     * 插入钱包的信息
     *
     * @param auditEntryListDetails
     * @param driverId
     */
    private void addWallet(AuditEntry auditEntryListDetails, Long driverId) {
        UserLoginResult userLoginResult = (UserLoginResult) TokenUtil.getTokenUserEntity(UserLoginResult.class);
        OaDWallet oaDWallet = new OaDWallet();
        oaDWallet.setWalletId(IDUtil.nextId());
        oaDWallet.setDriverId(driverId);
        oaDWallet.setOfficeId(userLoginResult.getOfficeId());
        oaDWallet.setTag(TokenUtil.getTag());
        oaDWallet.setCreateUser(TokenUtil.getTokenUserId());
        oaDWallet.setCreateTime(new Date());
        oaDWallet.setUpdateTime(new Date());
        int insert = oaDWalletMapper.insert(oaDWallet);
        if (insert == 0) {
            throw PangException.create(EErrorCode.addError);
        }
    }

    /**
     * 添加车辆信息
     *
     * @param auditEntryListDetails
     * @param driverId
     */
    private void addVehicleInfo(AuditEntry auditEntryListDetails, Long driverId) {
        long nextId = IDUtil.nextId();
        OaSysVehicle oaSysVehicle = new OaSysVehicle();
        oaSysVehicle.setVehicleId(nextId);
        oaSysVehicle.setVehNo(auditEntryListDetails.getCarNo());
        oaSysVehicle.setVehStatus(0);
        oaSysVehicle.setVehColor(Integer.parseInt(auditEntryListDetails.getColor()));
        oaSysVehicle.setCode(auditEntryListDetails.getVehCode());
        oaSysVehicle.setVehFuelType(auditEntryListDetails.getEngine());
        oaSysVehicle.setTag(TokenUtil.getTag());
        oaSysVehicle.setCreateUser(TokenUtil.getTokenUserId());
        oaSysVehicle.setCreateTime(new Date());
        oaSysVehicle.setUpdateTime(new Date());
        oaSysVehicle.setCityCode(auditEntryListDetails.getCityCode());
        oaSysVehicle.setVehicleOwnerId(driverId);
        oaSysVehicle.setVehicleOwnerId(driverId);
        oaSysVehicle.setVehType(auditEntryListDetails.getVehType());
        int insert = oaSysVehicleMapper.insert(oaSysVehicle);
        if (insert == 0) {
            throw PangException.create(EErrorCode.addError);
        }
        this.addDriverVehicle(auditEntryListDetails, driverId, nextId);

    }

    /**
     * 添加司机车辆关联信息
     *
     * @param auditEntryListDetails
     * @param driverId
     */
    private void addDriverVehicle(AuditEntry auditEntryListDetails, Long driverId, Long vehicleId) {
        OaDDriverVehicle oaDDriverVehicle = new OaDDriverVehicle();
        oaDDriverVehicle.setLinkedId(IDUtil.nextId());
        oaDDriverVehicle.setDriverId(driverId);
        oaDDriverVehicle.setVehicleId(vehicleId);
        oaDDriverVehicle.setIsUse(1);
        oaDDriverVehicle.setTag(TokenUtil.getTag());
        oaDDriverVehicle.setCreateUser(TokenUtil.getTokenUserId());
        oaDDriverVehicle.setCreateTime(new Date());
        oaDDriverVehicle.setUpdateTime(new Date());
        int insert = oaDDriverVehicleMapper.insert(oaDDriverVehicle);
        if (insert == 0) {
            throw PangException.create(EErrorCode.addError);
        }
    }

    /**
     * 添加机构
     */
    private void addOaDUserOffice(Long driverId, int officeCode) {
        QueryWrapper<OaSysOffice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysOffice.CODE, officeCode);
        List<OaSysOffice> oaSysOffices = oaSysOfficeMapper.selectList(queryWrapper);

        OaDUserOffice oaDUserOffice = new OaDUserOffice();
        oaDUserOffice.setLinkedId(IDUtil.nextId());
        oaDUserOffice.setDriverId(driverId);
        oaDUserOffice.setOfficeId(oaSysOffices.get(0).getOfficeId());
        oaDUserOffice.setTag(TokenUtil.getTag());
        oaDUserOffice.setCreateUser(TokenUtil.getTokenUserId());
        oaDUserOffice.setCreateTime(new Date());
        oaDUserOffice.setUpdateTime(new Date());
        int insert = oaDUserOfficeMapper.insert(oaDUserOffice);
        if (insert == 0) {
            throw PangException.create(EErrorCode.addError);
        }
    }

}
